/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.openbookformat.tags;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author MUFEED
 */
public class FnTextTag implements Tag {
    private String mark;
    private CompositeTag text;

    public FnTextTag(String mark, CompositeTag text) {
        this.mark = mark;
        this.text = text;
    }

    public String getMark() {
        return mark;
    }

    public void setMark(String mark) {
        this.mark = mark;
    }

    public CompositeTag getText() {
        return text;
    }

    public void setText(CompositeTag text) {
        this.text = text;
    }


    @Override
    public String toString() {
        String rVal = null;
        if(text.size() > 0) {
            rVal = "\t<fn_text mark='" + mark + "'>\n";
            for(int i = 0; i < text.size(); i++)
                    rVal += "\t\t" + text.getTag(i) + "\n";
            rVal += "\t</fn_text>";
            return rVal;
        }
        return "<fn_text mark='" + mark + "'>" + text.toString() + "</fn_text>";
    }
    
    public static final String TAG_PATTERN = 
            "(?s)<fn_text mark='(.*?)'>(.*?)</fn_text>";
    
    public static FnTextTag parse(String text) throws TagParsingException {
        if(!text.matches(TAG_PATTERN))
            throw new TagParsingException("Parsing error in FnTextTag:" + text);
        
        Pattern pattern = Pattern.compile(TAG_PATTERN);
        Matcher matcher = pattern.matcher(text);
       
        matcher.find();        
        String mark = matcher.replaceAll("$1");
        Text tTag = new Text(matcher.replaceAll("$2"));
        CompositeTag cTag = new CompositeTag();
        cTag.addTag(tTag);
        return new FnTextTag(mark, cTag);        
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final FnTextTag other = (FnTextTag) obj;
        if ((this.mark == null) ? (other.mark != null) : !this.mark.equals(other.mark)) {
            return false;
        }
        if (this.text != other.text && (this.text == null || !this.text.equals(other.text))) {
            return false;
        }
        return true;
    }
    
}
